const express = require("express");
const app = express();
const http = require("http");
const socketIo = require("socket.io");
const cors = require("cors");

const server = http.createServer(app)

 const socket = socketIo(server,{
    cors: '*'
 })

// data
 let userList = {}

 // methods
 // 接收offer信息
const offer = (data)=>{
    if(!userList[data.to]){
        userList[data.from].socket.emit('fail',{
            code: 1,
            msg: '对端不在线'
        })
        return
    }
    userList[data.to].socket.emit('offer',data)
}
 
// 接收answer信息
const answer = (data)=>{
    if(userList[data.to]){
        userList[data.to].socket.emit('answer',data)
    }
}
// 接收candidate信息
const candidate = (data)=>{
    console.log('xxssss',data);
    if(userList[data.to]){
        userList[data.to].socket.emit('candidate',data)
    }
}
// 取消注册
const close = (data)=>{
    userList[data.from].socket.disconnect()
}
// 视频电话挂断信令
const hangUp = (data)=>{
    userList[data.to].socket.emit('hangUp',data)
    userList[data.from].socket.emit('hangUp',data)
}
//  检查对端是否在线
const request = (data)=>{
    console.log('检测在线情况');
    if(!userList[data.to]){ 
        userList[data.from].socket.emit('fail',{
            code: 1,
            msg: '对端不在线'
        })
        console.log('检测在线情况-不在线');
        return
    }
    userList[data.from].socket.emit('success',{
        code: 0,
        msg: '对端在线'
    })
    console.log('检测在线情况-在线');
}
 // 连接成功
 socket.on('connection',(socket)=>{
    console.log("media服务连接成功",socket.handshake.query.userid);
    let userid = socket.handshake.query.userid
    //  存储用户编号及其socket连接,存在则断开原有连接存储新连接
    if(userList[userid]){
        userList[userid].socket.disconnect(true)
    }
    userList[userid] = {
        userid,socket
    }
    userList[userid].socket.emit('connection',{
        message: '连接成功',
        userid
    })
    userList[userid].socket.on('offer',offer)
    userList[userid].socket.on('answer',answer)
    userList[userid].socket.on('candidate',candidate)
    userList[userid].socket.on('close',close)
    userList[userid].socket.on('request',request)
    userList[userid].socket.on('hangUp',hangUp)
 })

 server.listen('9001',()=>{
    console.log("9001端口监听中");
 })
